/**
 * 性能优化工具类
 */

// 防抖函数
export function debounce(func, wait, immediate = false) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      timeout = null
      if (!immediate) func(...args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func(...args)
  }
}

// 节流函数
export function throttle(func, limit) {
  let inThrottle
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 图片懒加载
export function lazyLoadImage(imgSrc, placeholder = '/static/placeholder.png') {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => resolve(imgSrc)
    img.onerror = () => resolve(placeholder)
    img.src = imgSrc
  })
}

// 预加载关键资源
export function preloadResources(resources) {
  const promises = resources.map(resource => {
    if (resource.type === 'image') {
      return lazyLoadImage(resource.src)
    }
    return Promise.resolve()
  })
  return Promise.all(promises)
}

// 缓存管理
export class CacheManager {
  constructor(maxSize = 50) {
    this.cache = new Map()
    this.maxSize = maxSize
  }

  set(key, value) {
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value
      this.cache.delete(firstKey)
    }
    this.cache.set(key, value)
  }

  get(key) {
    const value = this.cache.get(key)
    if (value) {
      // 重新设置以更新访问时间
      this.cache.delete(key)
      this.cache.set(key, value)
    }
    return value
  }

  clear() {
    this.cache.clear()
  }
}

// 性能监控
export class PerformanceMonitor {
  constructor() {
    this.metrics = {}
  }

  startTiming(name) {
    this.metrics[name] = {
      startTime: Date.now()
    }
  }

  endTiming(name) {
    if (this.metrics[name]) {
      this.metrics[name].endTime = Date.now()
      this.metrics[name].duration = this.metrics[name].endTime - this.metrics[name].startTime
      console.log(`[性能监控] ${name}: ${this.metrics[name].duration}ms`)
    }
  }

  getMetrics() {
    return this.metrics
  }
}

// 内存管理
export function optimizeMemory() {
  // 清理未使用的数据
  if (typeof gc !== 'undefined') {
    gc()
  }
  
  // 清理定时器
  const highestTimeoutId = setTimeout(() => {}, 0)
  for (let i = 0; i < highestTimeoutId; i++) {
    clearTimeout(i)
  }
}

// 页面预加载
export function preloadPage(pagePath) {
  return new Promise((resolve, reject) => {
    uni.preloadPage({
      url: pagePath,
      success: resolve,
      fail: reject
    })
  })
}

// 批量预加载页面
export function preloadPages(pagePaths) {
  const promises = pagePaths.map(path => preloadPage(path))
  return Promise.allSettled(promises)
}
